package com.ruoyi.teaching.service.impl;

import com.alibaba.fastjson2.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.li.work.mapper.SysDeptMapper;
import com.ruoyi.li.work.mapper.SysUserMapper;
import com.ruoyi.li.work.mapper.SysUserRoleMapper;
import com.ruoyi.teaching.domain.*;
import com.ruoyi.teaching.domain.vo.*;
import com.ruoyi.teaching.mapper.PlatformCCourseMapper;
import com.ruoyi.teaching.mapper.PlatformQQuestionMapper;
import com.ruoyi.teaching.mapper.PlatformTScoreMapper;
import com.ruoyi.teaching.mapper.PlatformTTaskMapper;
import com.ruoyi.teaching.service.PlatformTScoreService;
import com.ruoyi.teaching.utils.UniversalUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 王旭
 * @since 2024-06-18
 */
@Service
public class PlatformTScoreServiceImpl extends ServiceImpl<PlatformTScoreMapper, PlatformTScore> implements PlatformTScoreService {

    @Autowired
    private PlatformTScoreMapper platformTScoreMapper;

    @Autowired
    private PlatformQQuestionMapper platformQQuestionMapper;

    @Autowired
    private PlatformTTaskMapper platformTTaskMapper;

    @Autowired
    private PlatformCCourseMapper platformCCourseMapper;

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private SysDeptMapper sysDeptMapper;

    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;

    /**
     * 根据ID查询作业信息
     *
     * @param id 作业ID
     * @return 查询结果
     */
    @Override
    public AjaxResult selectPlatformTScoreById(Long id) {
        // 根据ID查询作业信息
        PlatformTScore platformTScore = platformTScoreMapper.selectById(id);
        if (platformTScore == null) {
            return new AjaxResult(HttpStatus.ERROR, "作业信息有误，请联系管理员");
        }

        // 拷贝属性到VO对象
        PlatformTScoreVO platformTScoreVO = new PlatformTScoreVO();
        BeanUtils.copyProperties(platformTScore, platformTScoreVO);
        if (platformTScore.getTaskType() == 1) {
            platformTScoreVO.setStudentIntroduce(platformTScore.getScoreInfo());
        }

        // 解析并处理作业详情信息
        if (platformTScore.getTaskType() == 0) {
            List<ScoreInfoInVO> scoreInfoInVOS = JSONArray.parseArray(platformTScore.getScoreInfo(), ScoreInfoInVO.class);
            List<ScoreInfoOutVO> scoreInfoOutVOS = UniversalUtil.parseAndProcessScoreInformation(scoreInfoInVOS, platformQQuestionMapper);
            platformTScoreVO.setScoreInfo(scoreInfoOutVOS);
        }
        // 查询并设置相关的作业和课程信息
        setTaskAndCourse(platformTScore, platformTScoreVO);

        //处理学生的个人信息
        Long studentId = platformTScore.getStudentId().longValue();
        Long deptId = platformTScore.getDeptId().longValue();
        SysUser user = sysUserMapper.selectUserById(studentId);
        SysDept sysDept = sysDeptMapper.selectDeptById(deptId);
        if(user != null){
            platformTScoreVO.setStudentName(user.getNickName());
            platformTScoreVO.setAvatar(user.getAvatar());
        }else {
            platformTScoreVO.setStudentName("该学生已注销");
            platformTScoreVO.setAvatar("该学生已注销");
        }
        if(null != sysDept){
            platformTScoreVO.setDeptName(sysDept.getDeptName());
        }else {
            platformTScoreVO.setDeptName("该学生所属班级已注销");
        }

        // 获取当前时间
        Date nowDate = DateUtils.getNowDate();
        DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        // 设置作业的状态
        setTaskStatus(platformTScoreVO, format, nowDate);

        return new AjaxResult(HttpStatus.SUCCESS, "查询成功", platformTScoreVO);
    }


    /**
     * 查询教师发布的作业列表
     *
     * @param pageNum       页码
     * @param pageSize      每页大小
     * @param examName      考试名称
     * @param taskStatus    考试状态
     * @param vettingStatus 审核状态
     * @param deptId        部门ID
     * @param studentId     学生ID
     * @return 查询结果
     */
    @Override
    public AjaxResult selectPlatformTScoreListTeacher(
            Integer pageNum, Integer pageSize, String examName, Integer taskStatus,
            Integer vettingStatus, Integer deptId, Integer studentId
    ) {
        // 创建查询条件包装器和分页对象
        QueryWrapper<PlatformTScore> queryWrapper = new QueryWrapper<>();
        Page<PlatformTScore> page = new Page<>(pageNum, pageSize);

        // 获取当前教师ID
        int teacherId = SecurityUtils.getUserId().intValue();
        queryWrapper.eq("create_id", teacherId);

        // 添加查询条件（若有）
        if (StringUtils.isNotBlank(examName)) {
            queryWrapper.like("exam_name", examName);
        }
        if (taskStatus != null) {
            queryWrapper.eq("task_status", taskStatus);
        }
        if (vettingStatus != null) {
            queryWrapper.eq("vetting_status", vettingStatus);
        }
        if (deptId != null) {
            queryWrapper.eq("dept_id", deptId);
        }
        if (studentId != null) {
            queryWrapper.eq("student_id", studentId);
        }
        // 根据 id 字段倒序排序
        queryWrapper.orderByDesc("id");
        // 执行分页查询
        Page<PlatformTScore> resultPage = platformTScoreMapper.selectPage(page, queryWrapper);

        // 创建VO对象列表并设置相关属性
        List<PlatformTScoreVO> platformTScoreVOS = resultPage.getRecords().stream().map(record -> {
            PlatformTScoreVO platformTScoreVO = new PlatformTScoreVO();
            BeanUtils.copyProperties(record, platformTScoreVO);

            // 处理学生的个人信息
            SysUser user = sysUserMapper.selectUserById(record.getStudentId().longValue());
            SysDept sysDept = sysDeptMapper.selectDeptById(record.getDeptId().longValue());

            if(user != null){
                platformTScoreVO.setStudentName(user.getNickName());
                platformTScoreVO.setAvatar(user.getAvatar());
            }else {
                platformTScoreVO.setStudentName("该学生已注销");
                platformTScoreVO.setAvatar("该学生已注销");
            }
            if(null != sysDept){
                platformTScoreVO.setDeptName(sysDept.getDeptName());
            }else {
                platformTScoreVO.setDeptName("该学生所属班级已注销");
            }

            return platformTScoreVO;
        }).collect(Collectors.toList());

        // 设置分页信息
        Page<PlatformTScoreVO> platformTScoreVOPage = new Page<>(pageNum, pageSize);
        BeanUtils.copyProperties(resultPage, platformTScoreVOPage);
        platformTScoreVOPage.setRecords(platformTScoreVOS);

        return new AjaxResult(HttpStatus.SUCCESS, "查询成功", platformTScoreVOPage);
    }

    /**
     * 更新作业信息
     *
     * @param platformTScore 作业信息
     * @return 更新结果
     */
    @Override
    public AjaxResult updatePlatformTScore(PlatformTScore platformTScore) {
        // 获取现有的作业信息
        PlatformTScore existingScore = platformTScoreMapper.selectById(platformTScore.getId());
        if (existingScore == null) {
            return new AjaxResult(HttpStatus.ERROR, "作业信息不存在");
        }


        Long userId = SecurityUtils.getUserId();
        Long[] roleIds = sysUserRoleMapper.selectRoleIdbyUserId(userId);
        if (roleIds[0] == 4) {    // 学生身份进行判断
            // 检查学生的更新次数
            if (existingScore.getUpdateCount() >= 3) {
                return new AjaxResult(HttpStatus.ERROR, "作业修改次数已达上限，无法再修改");
            } else {
                // 更新 updateCount
                platformTScore.setUpdateCount(existingScore.getUpdateCount() + 1);
            }
            // 判断是否提交超时
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Integer taskId = platformTScore.getTaskId();
            PlatformTTask platformTTask = platformTTaskMapper.selectById(taskId);
            try {
                Date submitTime = format.parse(platformTScore.getEndTime());
                Date deadline = format.parse(platformTTask.getSubmitTime());
                if (deadline.before(submitTime)) {
                    return new AjaxResult(HttpStatus.ERROR, "提交时间已过，无法提交");
                }
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }

        //如果该作业审批过，那么updateCount直接变成3（应前端要求）
        if(platformTScore.getVettingStatus() == 1){
            platformTScore.setUpdateCount(3);
        }

        // 获取修改人信息
        UniversalCreateUpdate update = UniversalUtil.getCreateUpdate(sysUserMapper);
        platformTScore.setUpdateId(update.getId());
        platformTScore.setUpdateTime(DateUtils.getNowDate());
        platformTScore.setUpdateBy(update.getName());

        // 更新作业信息
        int updateResult = platformTScoreMapper.updateById(platformTScore);
        if (updateResult > 0) {
            return new AjaxResult(HttpStatus.SUCCESS, "更新成功");
        } else {
            return new AjaxResult(HttpStatus.ERROR, "更新失败");
        }
    }


    /**
     * 根据ID批量删除作业信息
     *
     * @param ids 作业ID数组
     * @return 删除结果
     */
    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public AjaxResult deletePlatformTScoreByIds(Long[] ids) {
        // 批量删除作业信息
        int deleteCount = platformTScoreMapper.deleteBatchIds(Arrays.asList(ids));
        if (deleteCount == ids.length) {
            return new AjaxResult(HttpStatus.SUCCESS, "删除成功");
        } else {
            throw new RuntimeException("删除失败");
        }
    }

    /**
     * 学生查询自己需要的作业
     *
     * @param pageNum                 页码
     * @param pageSize                每页大小
     * @param courseId                课程Id
     * @param vettingStatusAndIsClose 审批与结束状态（0全部，1待审批，2未结束，3已结束）
     * @return AjaxResult 包含分页信息和作业列表
     */
    @Override
    public AjaxResult selectPlatformTScoreListStudent(Integer pageNum, Integer pageSize, Integer courseId, Integer vettingStatusAndIsClose, String taskName) {
        // 获取当前学生ID
        int studentId = SecurityUtils.getUserId().intValue();

        // 创建查询条件包装器
        QueryWrapper<PlatformTScore> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("student_id", studentId); // 添加学生ID条件

        // 如果提供了课程ID，查询该课程的相关作业并添加条件
        if (courseId != null && courseId != 0) {
            List<Integer> taskIds = platformTTaskMapper.selectList(new QueryWrapper<PlatformTTask>().eq("task_course", courseId))
                    .stream().map(PlatformTTask::getId).collect(Collectors.toList());

            if (taskIds.isEmpty()) {
                return new AjaxResult(HttpStatus.SUCCESS, "该课程暂无作业", new Page<>(pageNum, pageSize));
            } else {
                queryWrapper.in("task_id", taskIds); // 添加作业ID条件
            }
        }

        if (StringUtils.isNotBlank(taskName)) {
            queryWrapper.like("task_name", taskName);
        }

        // 根据 id 字段倒序排序
        queryWrapper.orderByDesc("id");

        // 获取所有符合条件的成绩记录
        List<PlatformTScore> allPlatformTScores = platformTScoreMapper.selectList(queryWrapper);

        // 创建VO对象列表并设置相关属性
        List<PlatformTScoreVO> allPlatformTScoreVOS = allPlatformTScores.stream().map(platformTScore -> {
            PlatformTScoreVO platformTScoreVO = new PlatformTScoreVO();
            setTaskAndCourse(platformTScore, platformTScoreVO); // 设置作业和课程相关信息
            BeanUtils.copyProperties(platformTScore, platformTScoreVO); // 复制属性
            return platformTScoreVO;
        }).collect(Collectors.toList());

        // 获取当前时间
        Date nowDate = DateUtils.getNowDate();
        DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        // 设置每个作业的状态
        allPlatformTScoreVOS.forEach(platformTScoreVO -> setTaskStatus(platformTScoreVO, format, nowDate));

        // 根据审批与结束状态过滤作业
        List<PlatformTScoreVO> filteredPlatformTScoreVOS = filterTaskList(allPlatformTScoreVOS, vettingStatusAndIsClose);

        // 进行分页处理
        int total = filteredPlatformTScoreVOS.size();
        int start = Math.min((pageNum - 1) * pageSize, total);
        int end = Math.min(start + pageSize, total);

        // 获取当前页的数据
        List<PlatformTScoreVO> paginatedList = filteredPlatformTScoreVOS.subList(start, end);

        // 设置分页信息
        Page<PlatformTScoreVO> platformTScoreVOPage = new Page<>(pageNum, pageSize);
        platformTScoreVOPage.setRecords(paginatedList);
        platformTScoreVOPage.setTotal(total);

        // 返回结果
        return new AjaxResult(HttpStatus.SUCCESS, "操作成功", platformTScoreVOPage);
    }

    /**
     * 设置作业和课程相关信息
     *
     * @param platformTScore   作业对象
     * @param platformTScoreVO 作业视图对象
     */
    private void setTaskAndCourse(PlatformTScore platformTScore, PlatformTScoreVO platformTScoreVO) {
        PlatformTTask platformTTask = platformTTaskMapper.selectById(platformTScore.getTaskId());
        platformTScoreVO.setSubmitTime(platformTTask.getSubmitTime());

        PlatformCCourse platformCCourse = platformCCourseMapper.selectById(platformTTask.getTaskCourse());
        platformTScoreVO.setCourseName(platformCCourse.getCourseName());
        platformTScoreVO.setCourseId(platformCCourse.getId());
        platformTScoreVO.setCourseImage(platformCCourse.getCourseImage());
    }

    /**
     * 设置作业状态
     *
     * @param platformTScoreVO 作业视图对象
     * @param format           日期格式
     * @param nowDate          当前日期
     */
    private void setTaskStatus(PlatformTScoreVO platformTScoreVO, DateFormat format, Date nowDate) {
        try {
            String submitTime = platformTTaskMapper.selectById(platformTScoreVO.getTaskId()).getSubmitTime();
            Date submit = format.parse(submitTime);
            boolean before = nowDate.before(submit);
            // Status 0进行中，1超过时间的已结束，2待审核，3审核完成的已结束
            if (before) {
                platformTScoreVO.setStatus(0);
            } else {
                platformTScoreVO.setStatus(1);
            }
            if (platformTScoreVO.getVettingStatus() == 0 && platformTScoreVO.getTaskStatus() == 1) {
                platformTScoreVO.setStatus(2);
            }
            if (platformTScoreVO.getVettingStatus() == 1 && platformTScoreVO.getTaskStatus() == 1) {
                platformTScoreVO.setStatus(3);
            }
        } catch (ParseException e) {
            log.error("日期解析失败: " + platformTScoreVO.getSubmitTime(), e);
        }
    }

    /**
     * 根据审批与结束状态过滤作业列表
     *
     * @param platformTScoreVOS       作业视图对象列表
     * @param vettingStatusAndIsClose 审批与结束状态
     * @return 过滤后的作业视图对象列表
     */
    private List<PlatformTScoreVO> filterTaskList(List<PlatformTScoreVO> platformTScoreVOS, Integer vettingStatusAndIsClose) {
        if (vettingStatusAndIsClose == null) {
            return platformTScoreVOS;
        }

        return platformTScoreVOS.stream().filter(platformTScoreVO -> {
            switch (vettingStatusAndIsClose) {
                case 1:
                    return platformTScoreVO.getStatus() == 2;
                case 2:
                    return platformTScoreVO.getStatus() == 0;
                case 3:
                    return platformTScoreVO.getStatus() == 1 || platformTScoreVO.getStatus() == 3;
                default:
                    return true;
            }
        }).collect(Collectors.toList());
    }
}
